package com.chuhe.lottery.config;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @Author: 楚河
 * 分布式锁，工具类
 * @Date: 2025年05月03日16:36
 */
@Service
@Slf4j
public class LockService {
    @Autowired
    private RedissonClient redissonClient;

    @SneakyThrows
    public <T> T executeWithLock(String key, int waitTime, TimeUnit timeUnit, Supplier<T> supplier){
        RLock lock = redissonClient.getLock(key);
        boolean success = lock.tryLock(waitTime,timeUnit);
        if(!success){
            throw new RuntimeException("操作异常");
        }
        try {
            log.info("获取锁成功，key={}", lock);
            return supplier.get();
        }finally {
            lock.unlock();
        }
    }

    // 确保lockService.executeWithLock返回Supplier的结果
    public <T> T executeWithLock(String key, Supplier<T> supplier) {
        RLock lock = redissonClient.getLock(key);
        try {
            lock.lock();
            return supplier.get(); // 返回Supplier的结果
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
//    public <T> T executeWithLock(String key, Supplier<T> supplier) {
//        return executeWithLock(key, -1, TimeUnit.MILLISECONDS, supplier);
//    }
    public <T> T executeWithLock(String key, Runnable runnable) {
        return executeWithLock(key, 30, TimeUnit.MILLISECONDS, ()->{
            runnable.run();
            return null;
        });
    }
}
